package cz.data.domain.system.listener;

import cz.data.common.core.DataConstant;
import cz.data.common.core.RedisConstant;
import cz.data.common.redis.service.RedisService;
import cz.data.domain.system.dao.ConfigDao;
import cz.data.domain.system.model.entity.ConfigEntity;
import cz.data.domain.system.model.entity.QrtzJobEntity;
import cz.data.domain.system.quartz.utils.ScheduleUtil;
import cz.data.domain.system.service.QrtzJobService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Component
public class SpringEventListener {


    @EventListener(ApplicationReadyEvent.class)
    public void applicationReady(ApplicationReadyEvent event) {
        ConfigurableApplicationContext context = event.getApplicationContext();
        ConfigDao configDao = context.getBean(ConfigDao.class);
        RedisService redisService = context.getBean(RedisService.class);
        String configKey = RedisConstant.SYSTEM_CONFIG_KEY;
        Boolean hasConfigKey = redisService.hasKey(configKey);
        if (!hasConfigKey) {
            List<ConfigEntity> configEntityList = configDao.queryConfigList(DataConstant.EnableState.ENABLE.getKey());
            Map<String, Object> map = configEntityList.stream().collect(Collectors.toMap(ConfigEntity::getConfigKey, ConfigEntity::getConfigValue));
            redisService.hmset(configKey, map);
        }
        QrtzJobService qrtzJobService = context.getBean(QrtzJobService.class);
        // 项目启动时，初始化定时器
        List<QrtzJobEntity> list = qrtzJobService.activeQrtzJobs();
        ScheduleUtil.init(list);
    }

}
